<?
/*
in:rowed=row&ms=ms1||ms2||
out:.(*_*)text1$$text2(*_*).
*/

$rowed= isset($_POST['rowed']) ? intval($_POST['rowed']) : 0;
$ms= isset($_POST['ms'])       ?           $_POST['ms']  : "";
$length= isset($_POST['length']) ? $_POST['length'] : 0;
$typing= isset($_POST['typing']) ? $_POST['typing'] : 0;
$hasClickSendMail=(isset($_POST['SendEmail']) && $_POST['SendEmail']==1)? true : false;

// dua text vao neu co:
if($roomid>0 && !empty($ms))
{
	$arr=explode("||",$ms);
	for($i=0;$i<count($arr);$i++)
	{
		if(!empty($arr[$i]))
		{
			$sql_update="update ".$GLOBALS['first_table']."tblchat set 
						cText=concat(cText,'".$username."++".$arr[$i]."$$'),
						cGuestTyping='0||"._TIME."'
						where iChatId=$roomid";
			$dbsql->query($sql_update);
		}
	}
}

//update typing:
$sql_update="update ".$GLOBALS['first_table']."tblchat set 
			cGuestTyping='".$typing."||"._TIME."'
			where iChatId='$roomid'";
$dbsql->query($sql_update);


//lay text ra neu co:
for($u=0;$u<5;$u++)
{
	$data=LoadMsGuest();
	if($length==0 || (strlen($data)!=$length && strlen($text)>0))break;
	//usleep(500000);
	break;
}
echo $data;

//send email to guest if guest click send:

if($hasClickSendMail && $_SESSION['timeoldsendemail']<_TIME)
{
	$_SESSION['timeoldsendemail']=_TIME+50;
	$ssid= isset($_COOKIE[_NAMECOOKIELOGINGUEST]) ? $_COOKIE[_NAMECOOKIELOGINGUEST] : "";
	$sql_select="select * from ".$GLOBALS['first_table']."tblchat where cSId='$ssid' and iStatus=1";
	$rs=$dbsql->query($sql_select);
	if($result=$dbsql->fetch_array($rs))
	{	
		$to=$result['cEmail'];
		$to_name=$result['cRoomName'];
		$subject="Transcript of ".date("d M Y H:i:s").". Visitor: ".$to_name.". Operator: ".$_COOKIE[_NAMESITESUPPORT].".";
		
		$contentchat="";
		$contentarr=explode("$$",$result['cText']);
		foreach($contentarr as $key => $value)
		{
			if(trim($value)=="")continue;
			$arr2=explode("++",$value);
			$idchat=$arr2[0];
			$msgchat=$arr2[1];
			$color=($idchat==$GLOBALS['username'])? "006400": "B22222";
			$contentchat.="<span style='color:#808080'>".$idchat."</span>: <span style='color:#".$color."'>".$msgchat."</span><br>";
		}		
		$messenger="<center><h2>Chat Transcript</h2></center><br>";
		$messenger.=$contentchat;
		send_email($to,to_name,$subject,$messenger);
	}
}

exit();
?>